package com.ruijie.autotest.log.common.crypto;

import com.minelx.landisk.filesystem.core.File;
import com.minelx.util.IOUtil;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

import static com.minelx.landisk.filesystem.core.PathFactory.file;

public interface ICryptoFactory {
	Crypto encryption();

	Crypto decryption();

	default ICryptoFactory before(ICryptoFactory preprocess) {
		return new ICryptoFactory() {
			@Override
			public Crypto encryption() {
				return ICryptoFactory.this.encryption().before(preprocess.encryption());
			}

			@Override
			public Crypto decryption() {
				return preprocess.decryption().before(ICryptoFactory.this.decryption());
			}
		};
	}

	static List<File> decryptedFiles(List<File> decryptedFiles, Crypto decryption) throws Exception {
		List<File> result = new ArrayList<>();
		for (File decryptedFile : decryptedFiles) {
			System.out.println("decryptedFile = " + decryptedFile);
			try (InputStream inputStream = decryptedFile.inputStream()) {
				// FIXME 2021/1/13  move it to: StreamSet
				// FIXME: 2021/1/11  NEEDED REFACTORING !!!   duplicated with

				byte[] rawBytes = IOUtil.bytesOf(inputStream);
				byte[] decryptedAsBytes = decryption.doCrypto(rawBytes);
				File dest = decryptedFile.sibling("decrypted_" + decryptedFile.getName()).as(file());
				try (OutputStream outputStream = dest.outputStream(StandardOpenOption.CREATE)) {
					IOUtil.exchange(new ByteArrayInputStream(decryptedAsBytes), outputStream);
				}
				result.add(dest);
			}
		}
		return result;
	}
}
